const Koa = require('koa2');
const koaRouter = require('koa-router');
const cors = require('koa2-cors');
const static = require('koa-static');
const koaBody = require('koa-body');
const uploadimg = require('./uploadImg');
const render = require('koa-ejs');
const app = new Koa();
const router = koaRouter();
const path = require('path');

const {PORT} = require('./config');
const {IPv4Address} = require('../util/ip4address');
const {getPort} = require("./portIsOccupied");

render(app, {
  root: path.join(__dirname, './views'),
  layout: false,
  viewExt: 'html',
  cache: false,
  debug: false
});


router.get('/1', async ctx => {
  ctx.body = {
    name: 'hello'
  }
});

router.get('/ws', async ctx => {
  ctx.body = {
    IPv4Address,
    port:global.wsPort,
  }
});

router.get('/', async ctx => {
  await ctx.render('index', {
    IPv4Address,
    PORT:global.port,
  });
});
router.post('/upload1', async ctx => {
  console.error(ctx);
  ctx.body = {
    name: 'hello3'
  }
});

router.post('/upload', async function (ctx, next) {
  console.error(333333333333333333);
  const imgUrl = await uploadimg(ctx);
  if (imgUrl) {
    ctx.body = {
      url: imgUrl,
      message: '文件上传成功',
      code: '0',
    }
  } else {
    ctx.body = {
      url: imgUrl,
      message: '文件上传失败',
      code: '1',
    }
  }

});

app.use(cors());
/*app.use(cors({
    origin:"*",
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));*/

app.use(koaBody({
  multipart: true, // 支持文件上传
  formidable: {
    maxFieldsSize: 20000 * 1024 * 1024 * 1024 * 2, // 最大文件为2兆
    multipart: true // 是否支持 multipart-formdate 的表单
  }
}));
app.use(router.routes());
app.use(router.allowedMethods());

app.use(static(__dirname + '/public'));

getPort().then((port) => {
  console.log("node js 服务开启 http://" + IPv4Address + ":" + port);
  global.port = port;
  app.listen(port);
}).catch((e) => {
  console.error('&&&&&&&&&&&&&&&&', e)
});

console.log('正在准备启动服务');

